package io.xxx.xbutler.domain.task;

import io.xxx.xbutler.domain.Robot;
import io.xxx.xbutler.domain.Store;
import jakarta.annotation.Nonnull;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

@Data
public class PushContext {

    private Long taskReceiverId;

    private Task task;

    /**
     * 多条消息时，消息需要按照顺序发送
     */
    private List<TaskItem> taskItems;

    private Receiver receiver;

    private Robot robot;

    private Store store;

    private Store cutomStore;

    private Long checkElapsedTime;

    private Map<String, String> trackData;

    public void addTrackData(String key, String value) {
        if (trackData == null) {
            trackData = new ConcurrentHashMap<>();
        }
        trackData.put(key, value);
    }

    public PushRecord toPushRecord(@Nonnull Supplier<Long> idWorker, LocalDateTime now) {
        return new PushRecord()
                .setId(idWorker.get())
                .setTaskId(task.getId())
                .setTaskReceiverId(taskReceiverId)
                .setReceiverType(receiver.getType())
                .setReceiverId(receiver.getId())
                .setReceiverName(receiver.getName())
                .setStoreId(receiver.getStoreId())
                .setStoreCode(receiver.getStoreCode())
                .setStoreName(receiver.getStoreName())
                .setRobotId(robot.getId())
                .setRobotName(robot.getName())
                .setCreatedTime(now)
                .setUpdatedTime(now);
    }

    public List<PushRecordItem> toPushRecordItems(@Nonnull Supplier<Long> idWorker, Long recordId, LocalDateTime now) {
        return taskItems.stream()
                .map(it -> {
                    PushRecordItem item = new PushRecordItem();
                    BeanUtils.copyProperties(it, item);
                    item.setId(idWorker.get());
                    item.setRecordId(recordId);
                    item.setTaskId(task.getId());
                    item.setTaskItemId(it.getId());
                    item.setReceiverType(receiver.getType().name());
                    item.setReceiverId(receiver.getId());
                    item.setRobotId(robot.getId());
                    item.setPushStartTime(now);
                    item.setStatus(SendStatus.UNKNOWN);
                    item.setCreatedTime(now);
                    item.setUpdatedTime(now);
                    return item;
                })
                .toList();
    }
}
